import storage from 'store'
import { login, getInfo, logout } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const user = {
  state: {
    token: '',
    name: '',
    avatar: '',
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name }) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(response => {
            if (response.code === 1) {
              const result = response.data
              storage.set(ACCESS_TOKEN, result, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result)
              resolve()
            } else {
              reject(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(response => {
            if (response.code === 1) {
              const result = response.data
              if (!result.info) {
                reject(new Error('查询用户信息失败'))
                return
              }
              /* 个人信息 */
              commit('SET_INFO', result.info)
              /* 名称 */
              commit('SET_NAME', { name: result.info.nickName })
              /* 头像 */
              commit('SET_AVATAR', result.info.headerImg)
              resolve(result.routers)
            } else {
              reject(new Error('查询用户信息失败'))
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise(resolve => {
        logout(state.token)
          .then(() => {
            commit('SET_TOKEN', '')
            commit('SET_NAME', { name: '' })
            storage.remove(ACCESS_TOKEN)
            resolve()
          })
          .catch(() => {
            resolve()
          })
          .finally(() => {})
      })
    }
  }
}

export default user
